package org.jeecg.modules.yfGyfwh.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.yfFdxx.entity.HqYfFdxx;
import org.jeecg.modules.yfFdxx.service.IHqYfFdxxService;
import org.jeecg.modules.yfFenfgl.entity.HqYfFenfgl;
import org.jeecg.modules.yfFenfgl.service.IHqYfFenfglService;
import org.jeecg.modules.yfYqgk.entity.HqYfYqgk;
import org.jeecg.modules.yfYqgk.service.IHqYfYqgkService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.yfGyfwh.entity.HqYfGyfwhJbqk;
import org.jeecg.modules.yfGyfwh.entity.HqYfGyfwhRyxx;
import org.jeecg.modules.yfGyfwh.entity.HqYfGyfwh;
import org.jeecg.modules.yfGyfwh.vo.HqYfGyfwhPage;
import org.jeecg.modules.yfGyfwh.service.IHqYfGyfwhService;
import org.jeecg.modules.yfGyfwh.service.IHqYfGyfwhJbqkService;
import org.jeecg.modules.yfGyfwh.service.IHqYfGyfwhRyxxService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 营区公寓房维护
 * @Author: jeecg-boot
 * @Date:   2020-07-12
 * @Version: V1.0
 */
@Api(tags="营区公寓房维护")
@RestController
@RequestMapping("/yfGyfwh/hqYfGyfwh")
@Slf4j
public class HqYfGyfwhController {
	@Autowired
	private IHqYfGyfwhService hqYfGyfwhService;
	@Autowired
	private IHqYfGyfwhJbqkService hqYfGyfwhJbqkService;
	@Autowired
	private IHqYfGyfwhRyxxService hqYfGyfwhRyxxService;
	@Autowired
	private IHqYfFdxxService hqYfFdxxService;
	@Autowired
	private IHqYfYqgkService hqYfYqgkService;
	@Autowired
	private IHqYfFenfglService hqYfFenfglService;




	 @AutoLog(value = "分房管理根据姓名赋值")
	 @ApiOperation(value="分房管理赋值", notes="分房管理赋值")
	 @GetMapping(value = "/assignment")
	 public Result<?> assignment(HqYfFenfgl hqYfFenfgl,
								 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="999") Integer pageSize,
								 HttpServletRequest req) {
		 System.out.println("姓名--------------------------"+hqYfFenfgl.getXingm());
		 QueryWrapper<HqYfFenfgl> queryWrapper = QueryGenerator.initQueryWrapper(hqYfFenfgl, req.getParameterMap()).eq("process_status",2);
		 Page<HqYfFenfgl> page = new Page<>(pageNo,pageSize);
		 IPage<HqYfFenfgl> iPage = hqYfFenfglService.page(page, queryWrapper);
		 System.out.println("返回的数据："+iPage);
		 return Result.ok(iPage);
	 }

	 @AutoLog(value = "营区公寓房楼栋-分页列表查询")
	 @ApiOperation(value="营区公寓房楼栋-分页列表查询", notes="营区公寓房楼栋-分页列表查询")
	 @GetMapping(value = "/loud")
	 public Result<?> queryPageLoud(HqYfFdxx hqYfFdxx,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="999") Integer pageSize,
									HttpServletRequest req) {
		 System.out.println("................................"+hqYfFdxx);
		 HqYfYqgk hqYfYqgk = new HqYfYqgk();
		 hqYfYqgk.setYingqmc(hqYfYqgk.getYingqmc()+"");
		 Page<HqYfYqgk> page1= new Page<HqYfYqgk>(pageNo, pageSize);
		 QueryWrapper<HqYfYqgk> hqYfYqgkQueryWrapper = QueryGenerator.initQueryWrapper(hqYfYqgk, req.getParameterMap());
		 IPage<HqYfYqgk> pageList1 = hqYfYqgkService.page(page1, hqYfYqgkQueryWrapper);
		 /*根据栋号排序*/
		 QueryWrapper<HqYfFdxx> queryWrapper = QueryGenerator.initQueryWrapper(hqYfFdxx, req.getParameterMap()).orderByAsc("dongh");
		 Page<HqYfFdxx> page = new Page<HqYfFdxx>(pageNo, pageSize);
		 IPage<HqYfFdxx> pageList = hqYfFdxxService.page(page, queryWrapper);

		 return Result.ok(pageList);
	 }

	/**
	 * 分页列表查询
	 *
	 * @param hqYfGyfwh
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-分页列表查询")
	@ApiOperation(value="营区公寓房维护-分页列表查询", notes="营区公寓房维护-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HqYfGyfwh hqYfGyfwh,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<HqYfGyfwh> queryWrapper = QueryGenerator.initQueryWrapper(hqYfGyfwh, req.getParameterMap());
		Page<HqYfGyfwh> page = new Page<HqYfGyfwh>(pageNo, pageSize);
		IPage<HqYfGyfwh> pageList = hqYfGyfwhService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hqYfGyfwhPage
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-添加")
	@ApiOperation(value="营区公寓房维护-添加", notes="营区公寓房维护-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HqYfGyfwhPage hqYfGyfwhPage) {
		System.out.println("公寓房维护:"+hqYfGyfwhPage);
		/*将楼栋-单元号-房间号合并*/
		hqYfGyfwhPage.setDongdf(hqYfGyfwhPage.getDongh()+"-"+hqYfGyfwhPage.getDanyh()+"-"+hqYfGyfwhPage.getFangj());
		double pay = pay(hqYfGyfwhPage.getQissj(), hqYfGyfwhPage.getXianjsj(), hqYfGyfwhPage.getFangzbz(), hqYfGyfwhPage.getArea());
		Double yij = hqYfGyfwhPage.getYij();
		if (null == yij){
			yij = 0.0;
			hqYfGyfwhPage.setYij(yij);
		}
		Double qianj = hqYfGyfwhPage.getQianj();
		qianj = pay - yij;
		hqYfGyfwhPage.setYingj(pay);
		hqYfGyfwhPage.setQianj(qianj);

		System.out.println("应该缴费::::::::::::"+pay);
		System.out.println("已经缴费::::::::::::"+yij);
		System.out.println("欠缴费::::::::::::"+qianj);

		HqYfGyfwh hqYfGyfwh = new HqYfGyfwh();
		BeanUtils.copyProperties(hqYfGyfwhPage, hqYfGyfwh);
		System.out.println("公寓房维护"+hqYfGyfwh);
		hqYfGyfwhService.saveMain(hqYfGyfwh, hqYfGyfwhPage.getHqYfGyfwhJbqkList(),hqYfGyfwhPage.getHqYfGyfwhRyxxList());
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hqYfGyfwhPage
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-编辑")
	@ApiOperation(value="营区公寓房维护-编辑", notes="营区公寓房维护-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HqYfGyfwhPage hqYfGyfwhPage) {
		/*将楼栋-单元号-房间号合并*/
		hqYfGyfwhPage.setDongdf(hqYfGyfwhPage.getDongh()+"-"+hqYfGyfwhPage.getDanyh()+"-"+hqYfGyfwhPage.getFangj());
		double pay = pay(hqYfGyfwhPage.getQissj(), hqYfGyfwhPage.getXianjsj(), hqYfGyfwhPage.getFangzbz(), hqYfGyfwhPage.getArea());
		Double yij = hqYfGyfwhPage.getYij();
		if (null == yij){
			yij = 0.0;
			hqYfGyfwhPage.setYij(yij);
		}
		Double qianj = hqYfGyfwhPage.getQianj();
		qianj = pay - yij;
		hqYfGyfwhPage.setYingj(pay);
		hqYfGyfwhPage.setQianj(qianj);

		System.out.println("应该缴费::::::::::::"+pay);
		System.out.println("已经缴费::::::::::::"+yij);
		System.out.println("欠缴费::::::::::::"+qianj);

		HqYfGyfwh hqYfGyfwh = new HqYfGyfwh();
		BeanUtils.copyProperties(hqYfGyfwhPage, hqYfGyfwh);
		HqYfGyfwh hqYfGyfwhEntity = hqYfGyfwhService.getById(hqYfGyfwh.getId());
		if(hqYfGyfwhEntity==null) {
			return Result.error("未找到对应数据");
		}
		System.out.println("修改的数据："+hqYfGyfwh);
		hqYfGyfwhService.updateMain(hqYfGyfwh, hqYfGyfwhPage.getHqYfGyfwhJbqkList(),hqYfGyfwhPage.getHqYfGyfwhRyxxList());
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-通过id删除")
	@ApiOperation(value="营区公寓房维护-通过id删除", notes="营区公寓房维护-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		hqYfGyfwhService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-批量删除")
	@ApiOperation(value="营区公寓房维护-批量删除", notes="营区公寓房维护-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hqYfGyfwhService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "营区公寓房维护-通过id查询")
	@ApiOperation(value="营区公寓房维护-通过id查询", notes="营区公寓房维护-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HqYfGyfwh hqYfGyfwh = hqYfGyfwhService.getById(id);
		if(hqYfGyfwh==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(hqYfGyfwh);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公寓房基本情况通过主表ID查询")
	@ApiOperation(value="公寓房基本情况主表ID查询", notes="公寓房基本情况-通主表ID查询")
	@GetMapping(value = "/queryHqYfGyfwhJbqkByMainId")
	public Result<?> queryHqYfGyfwhJbqkListByMainId(@RequestParam(name="id",required=true) String id) {
		List<HqYfGyfwhJbqk> hqYfGyfwhJbqkList = hqYfGyfwhJbqkService.selectByMainId(id);
		return Result.ok(hqYfGyfwhJbqkList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公寓房人员信息通过主表ID查询")
	@ApiOperation(value="公寓房人员信息主表ID查询", notes="公寓房人员信息-通主表ID查询")
	@GetMapping(value = "/queryHqYfGyfwhRyxxByMainId")
	public Result<?> queryHqYfGyfwhRyxxListByMainId(@RequestParam(name="id",required=true) String id) {
		List<HqYfGyfwhRyxx> hqYfGyfwhRyxxList = hqYfGyfwhRyxxService.selectByMainId(id);
		return Result.ok(hqYfGyfwhRyxxList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hqYfGyfwh
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqYfGyfwh hqYfGyfwh) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<HqYfGyfwh> queryWrapper = QueryGenerator.initQueryWrapper(hqYfGyfwh, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<HqYfGyfwh> queryList = hqYfGyfwhService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<HqYfGyfwh> hqYfGyfwhList = new ArrayList<HqYfGyfwh>();
      if(oConvertUtils.isEmpty(selections)) {
          hqYfGyfwhList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          hqYfGyfwhList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<HqYfGyfwhPage> pageList = new ArrayList<HqYfGyfwhPage>();
      for (HqYfGyfwh main : hqYfGyfwhList) {
          HqYfGyfwhPage vo = new HqYfGyfwhPage();
          BeanUtils.copyProperties(main, vo);
          List<HqYfGyfwhJbqk> hqYfGyfwhJbqkList = hqYfGyfwhJbqkService.selectByMainId(main.getId());
          vo.setHqYfGyfwhJbqkList(hqYfGyfwhJbqkList);
          List<HqYfGyfwhRyxx> hqYfGyfwhRyxxList = hqYfGyfwhRyxxService.selectByMainId(main.getId());
          vo.setHqYfGyfwhRyxxList(hqYfGyfwhRyxxList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "营区公寓房维护列表");
      mv.addObject(NormalExcelConstants.CLASS, HqYfGyfwhPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("营区公寓房维护数据", "导出人:"+sysUser.getRealname(), "营区公寓房维护"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<HqYfGyfwhPage> list = ExcelImportUtil.importExcel(file.getInputStream(), HqYfGyfwhPage.class, params);
              for (HqYfGyfwhPage page : list) {
                  HqYfGyfwh po = new HqYfGyfwh();
                  BeanUtils.copyProperties(page, po);
                  hqYfGyfwhService.saveMain(po, page.getHqYfGyfwhJbqkList(),page.getHqYfGyfwhRyxxList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:请检查导入文件的格式或字段是否匹配！"
//					  +e.getMessage()
			  );

          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
   public double pay (Date str , Date end , String fangz , Double area){
    	if (null == str || null == end || null == area || null == fangz){
    		return 0;
		}
//    	房租每月没平米
	   Double housePrice = Double.parseDouble(fangz);
//    	相差的天数
	   long dayDiff = (end.getTime() - str.getTime()) / (1000 * 24 * 3600);
//	   费用
	   return Math.ceil(dayDiff * area * housePrice/30);
   }

}
